import Vue from 'vue'
import Router from 'vue-router'

// 3.引用组件
import layout from '@/layout'
import store from '@/store'

Vue.use(Router)

// 树装结构组装 为 树状路由结构
function menu2Component (localMenu) {
  let result = []
  if (localMenu) {
    result = localMenu.reduce((arr, item) => {
      if (item.children && item.children.length) {
        return [...arr, {
          name: item.name,
          path: item.path,
          children: menu2Component(item.children)
        }]
      } else {
        return [...arr, {
          name: item.name,
          path: item.path,
          component: (resolve) => require(['@/views/' + item.component], resolve)
        }]
      }
    }, [])
  }
  return result
}

// 注册到路由中
export function addRoutes (localMenu) {
  if (localMenu) {
    let menus = menu2Component(localMenu)
    if (menus) {
      menus.forEach(element => {
        let chd = element.children
        if (chd && chd.length) {
          chd.forEach(m => router.addRoute('layout', m))
        } else {
          router.addRoute('layout', element)
        }
      })
    }
  }
}

// 不在layout 中定义的组件都是最大化的页面
const router = new Router({
  mode: 'history',
  routes: [
    {
      path: '/',
      name: 'layout',
      component: layout,
      children: []
    },
    {
      path: '/login',
      name: 'login',
      component: (resolve) => require(['@/views/login'], resolve)
    },
    {
      path: '/404',
      name: '404',
      component: (resolve) => require(['@/views/404'], resolve),
      hidden: true
    },
    {
      path: '*',
      redirect: '/404'
    }
  ]
})


// 如果用户信息存在,则加载路由---浏览器刷新,会走这个逻辑
let menus = store.getMenus()
if (menus) {
  // 本地菜单
  addRoutes(menus)
  console.log('已登录-router.js加载路由信息')
}

// 防止连续点击多次路由报错
let routerPush = Router.prototype.push
Router.prototype.push = function push (location) {
  return routerPush.call(this, location).catch(err => err)
}
export default router
